package mo.tags.dp;

import java.util.ArrayList;
import java.util.List;

public class L22 {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        build(res, new StringBuilder(), 0, 0, n);
        return res;
    }


    private void build(List<String> res, StringBuilder builder, int left, int right, int n) {
        if (builder.length() == n*2) {
            res.add(builder.toString());
            return;
        }
        if (left < n) {
            builder.append("(");
            build(res, builder, left+1, right, n);
            builder.deleteCharAt(builder.length()-1);
        }
        if (right < left) {
            builder.append(")");
            build(res, builder, left, right+1, n);
            builder.deleteCharAt(builder.length()-1);
        }
    }

    public static void main(String[] args) {
        L22 test = new L22();
        System.out.println(test.generateParenthesis(3));
    }


}
